package com.mbbb.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.mbbb.yygh.oss.service.FileUploadService;
import com.mbbb.yygh.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Override
    public String uploadFile(MultipartFile file) {

        // 设置固定值
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketname = ConstantPropertiesUtil.BUCKET_NAME;

        try {

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();

            // 在文件名称中设置唯一值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            filename = uuid + filename;

            // 根据当前日期进行分组
            // 例：2021/12/18/mm1.jpg
            String date = new DateTime().toString("yyyy/MM/dd");
            filename = date + "/" + filename;


            // Bucket名称，上传的文件的路径和名称，文件的输入流
            ossClient.putObject(bucketname, filename, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //返回上传文件在阿里云中的路径
            //https://hospital0918.oss-cn-beijing.aliyuncs.com/mm2.jpg
            String url = "http://"+bucketname+"."+endpoint+"/"+filename;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
